<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------

/**
 * 保存临时验证码
 * @param int $len
 * @param int $id
 * @return string
 */
function setVCode(int $len = 4, int $id = 0): string {
    $client = getClient();
    if ($id === 0) {
        //自动ID，则使用SessionId
        $key = $client->getSessionId();
    } else {
        //指定ID
        $ip = $client->ip;
        $key = md5($ip.$id);
    }
    $value = \Inphp\Core\Util\Str::randomString($len);
    \Inphp\Core\Db\Redis::set("VCode_".$key, strtoupper($value), 5 * 60);
    return $value;
}

/**
 * 验证
 * @param int $id
 * @param string $value
 * @return bool
 */
function matchVCode(string $value, int $id = 0): bool {
    $client = getClient();
    $id = max(0, $id);
    if ($id === 0) {
        //自动ID，则使用SessionId
        $key = $client->getSessionId();
    } else {
        //指定ID
        $ip = $client->ip;
        $key = md5($ip.$id);
    }
    $cache = \Inphp\Core\Db\Redis::get("VCode_".$key);
    if (!empty($cache) && strtoupper($value) == $cache) {
        //已使用，作废
        \Inphp\Core\Db\Redis::del("VCode_".$key);
        return true;
    }
    return false;
}

/**
 * 生成临时验证码
 * @param string|null $name
 * @return string
 */
function setTempVCode(?string $name): string {
    $name = $name ?? "tempVCode";
    $user = authUserInfo();
    $uid = $user ? $user["uid"] : 0;
    $name .= $uid;
    $number = \Inphp\Core\Util\Str::randomNumber(6);
    //临时180秒内有效
    \Inphp\Core\Db\Redis::set($name, $number, 180);
    return $number;
}

/**
 * 获取临时验证码
 * @param string|null $name
 * @param int $uid
 * @return string
 */
function getTempVCode(?string $name, int $uid = 0): string {
    $name = $name ?? "tempVCode";
    $name .= $uid;
    return \Inphp\Core\Db\Redis::get($name) ?? "";
}

/**
 * 匹配临时验证码
 * @param string $value
 * @param string|null $name
 * @param int $uid
 * @return bool
 */
function matchTempVCode(string $value, ?string $name, int $uid = 0): bool {
    if (empty($value) || strlen($value) !== 6) {
        return false;
    }
    return $value == getTempVCode($name, $uid);
}